<template>
    <div style="height: 100vh">
        <el-row class="search-box">
            <el-button @click="openQueryDialog" type="primary" size="mini">查询</el-button>
            <el-button @click="handleExport" type="primary" size="mini">导出</el-button>
            <el-button type="primary" size="mini" @click="layoutDialog = true">布局设置</el-button>
        </el-row>
        <el-row class="table-box" style="border: 1px solid #d7d7d7">
            <!-- <keep-alive include="test-keep-alive"> -->
            <div style="height: calc(100vh - 122px)">
                <el-table
                    :key="tableKey"
                    v-loading="loading"
                    element-loading-text="拼命加载中"
                    :data="stocktableData"
                    border
                    size="mini"
                    style="width: 100%"
                    height="100%"
                    ref="table"
                    row-key="stockCode"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column align="center" type="selection" :reserve-selection="true" width="50" size="mini"> </el-table-column>
                    <template v-for="(item, index) in showFieldList.length ? showFieldList : tableColumns">
                        <el-table-column
                            show-overflow-tooltip
                            :key="'name' + index"
                            :label="item.content"
                            :prop="item.id"
                            :render-header="renderHeader"
                        >
                            <template slot-scope="scope">
                                <span v-if="['listDays', 'listDays2', 'totalAmount', 'turnoverAmount'].includes(item.id)" style="float: right;">
                                    {{ numberFormat(scope.row[item.id]) || '--' }}
                                </span>
                                <span v-else-if="['totalValue', 'turnoverValue', 'facePrice'].includes(item.id)" style="float: right;">
                                    {{ numberFormat(scope.row[item.id], 2) || '--' }}
                                </span>
                                <span v-else-if="item.id === 'stockType'">
                                    {{ stockType[scope.row[item.id]] || '--' }}
                                </span>
                                <span v-else-if="item.id === 'mixedType_1'">
                                    <!-- {{ scope.row.categoryType === 'ZQ' ? bondMixedTypeMapping[scope.row.mixedType] || '--' : '--' }} -->

                                    {{ scope.row.categoryType === 'ZQ' ? handleParams(bondMixedTypeMapping, scope.row.mixedType) || '--' : '--' }}
                                </span>
                                <span v-else-if="item.id === 'mixedType_2'">
                                    {{ scope.row.categoryType === 'JJ' ? handleParams(fundMixedTypeMapping, scope.row.mixedType) || '--' : '--' }}
                                    <!-- {{ scope.row.categoryType === 'JJ' ? fundMixedTypeMapping[scope.row.mixedType] || '--' : '--' }} -->
                                </span>
                                <span v-else-if="item.id === 'mixedType_3'">
                                    <!-- {{ scope.row.mixedType ? mixedTypeMapping[scope.row.mixedType] || '--' : '--' }} -->
                                    {{ scope.row.mixedType ? handleParams(mixedTypeMapping, scope.row.mixedType) || '--' : '--' }}
                                </span>
                                <span v-else-if="item.id === 'moreType_1'">
                                    <!-- {{ scope.row.categoryType === 'ZQ' ? bondMoreTypeMapping[scope.row.moreType.trim()] || '--' : '--' }} -->
                                    {{
                                        scope.row.categoryType === 'ZQ' ? handleParams(bondMoreTypeMapping, scope.row.moreType.trim()) || '--' : '--'
                                    }}
                                </span>
                                <span v-else-if="item.id === 'moreType_2'">
                                    {{
                                        scope.row.categoryType === 'JJ' ? handleParams(fundMoreTypeMapping, scope.row.moreType.trim()) || '--' : '--'
                                    }}
                                    <!-- {{ scope.row.categoryType === 'JJ' ? fundMoreTypeMapping[scope.row.moreType.trim()] || '--' : '--' }} -->
                                </span>
                                <span v-else-if="item.id === 'moreType_3'">
                                    <!-- {{ scope.row.moreType ? stockMoreTypeMapping[scope.row.moreType.trim()] || '--' : '--' }} -->
                                    {{ scope.row.moreType ? handleParams(stockMoreTypeMapping, scope.row.moreType.trim()) || '--' : '--' }}
                                </span>
                                <span v-else-if="item.id === 'calculateValue' || item.id === 'thresholdValue'">{{
                                    scope.row[item.id] != undefined
                                        ? numberFormat(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit)
                                        : '--'
                                }}</span>
                                <span v-else>{{ scope.row[item.id] || '--' }}</span>
                                <!-- <span>{{ scope.row[item.id] }}</span> -->
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div class="block">
                <risk-pagination :paging="stockPage" @page-change="currentChange"></risk-pagination>
            </div>
        </el-row>

        <yh-dialog title="查询证券信息" :visible.sync="queryDialog" width="650px" drag @close="queryDialog = false" :close-on-click-modal="false">
            <el-form label-width="100px" size="mini" ref="queryForm" :model="queryForm">
                <div>
                    <el-form-item label="交易市场" prop="marketCode">
                        <el-select style="width: 185px" v-model="queryForm.marketCode" multiple filterable collapse-tags placeholder="请选择">
                            <el-option
                                v-for="item in marketCodeSelectData"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码" prop="stockCode">
                        <el-input v-model="queryForm.stockCode" style="width: 185px" placeholder="支持','分割"></el-input>
                    </el-form-item>
                    <el-form-item label="证券名称" prop="stockName">
                        <el-input v-model="queryForm.stockName" style="width: 185px"></el-input>
                    </el-form-item>
                    <el-form-item label="资产类别" prop="categoryType">
                        <el-select style="width: 185px" v-model="queryForm.categoryType" multiple collapse-tags placeholder="请选择">
                            <el-option
                                v-for="item in categoryData"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="证券类别" prop="stockType">
                        <el-select style="width: 185px" v-model="queryForm.stockType" multiple collapse-tags filterable placeholder="请选择">
                            <el-option
                                v-for="item in stockTypeSelectData"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="更多分类" prop="moreType">
                        <el-select style="width: 185px" v-model="queryForm.moreType" collapse-tags multiple filterable placeholder="请选择">
                            <el-option
                                v-for="item in moreTypeSelectData"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="杂项分类" prop="mixedType">
                        <el-select style="width: 185px" v-model="queryForm.mixedType" collapse-tags multiple filterable placeholder="请选择">
                            <el-option
                                v-for="item in mixTypeSelectData"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="queryDialog = false"> 取 消 </el-button>
                <el-button size="mini" @click="resetForm"> 重 置 </el-button>
                <el-button size="mini" type="primary" @click="submitQueryForm"> 确 定 </el-button>
            </div>
        </yh-dialog>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="TN_STOCK"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';

import { downLoadFile } from '@/utils/request';
import { numberFormat, unitShow } from '@/utils/tools';
import { PageVO } from '@yhfin/biz';
import draggable from 'vuedraggable';
import Index from './dict';
import DictionConstUtil, { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { getDictByCodes } from '../baseparam/api/index';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
type TFieldItem = { id: string; content: string };

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'StockInfo',
    components: {
        draggable,
        RiskTableLayout,
        RiskPagination,
    },
})
export default class StockInfo extends Vue {
    numberFormat = numberFormat;
    unitShow = unitShow;
    private categoryData = [
        {
            dictKeyName: '基金',
            dictKey: 'JJ',
        },
        {
            dictKeyName: '权证',
            dictKey: 'QZ',
        },
        {
            dictKeyName: '存款',
            dictKey: 'CK',
        },
        {
            dictKeyName: '理财',
            dictKey: 'CP',
        },
        {
            dictKeyName: '股票',
            dictKey: 'GP',
        },
        {
            dictKeyName: '回购',
            dictKey: 'HG',
        },
        {
            dictKeyName: '债券',
            dictKey: 'ZQ',
        },
        {
            dictKeyName: '期货',
            dictKey: 'QH',
        },
        {
            dictKeyName: '其他',
            dictKey: 'QT',
        },
    ] as const;

    private stocktableData: any[] = [];

    private stockPage: pages = {
        total: 0,
        pageSize: 50,
        currentPage: 1,
    };

    private stockCode: string = '';

    private stockPageVO: PageVO = new PageVO();

    private stockCodeList: any[] = [];

    private queryDialog: boolean = false;

    private layoutDialog: boolean = false;

    private queryForm = {
        categoryType: [],
        marketCode: [],
        mixedType: [],
        moreType: [],
        paging: {
            currentPage: 1,
            pageSize: 50,
        },
        stockCode: '',
        stockCodes: [],
        stockName: '',
        stockType: [],
    };

    // 全部表格列
    private tableColumns: any[] = [
        { content: '交易市场', id: 'marketName' },
        { content: '证券代码', id: 'stockCode' },
        { content: '证券简称', id: 'stockNameSt' },
        { content: '证券全称', id: 'stockName' },
        { content: '上市天数', id: 'listDays' },
        { content: '上市天数(交易日)', id: 'listDays2' },
        { content: '资产类别', id: 'categoryTypeName' },
        { content: '证券类别', id: 'stockType' },
        { content: '债券杂项分类', id: 'mixedType_1' },
        { content: '基金杂项分类', id: 'mixedType_2' },
        { content: '证券杂项分类', id: 'mixedType_3' },
        { content: '债券更多分类', id: 'moreType_1' },
        { content: '基金更多分类', id: 'moreType_2' },
        { content: '证券更多分类', id: 'moreType_3' },
        { content: '总股本', id: 'totalAmount' },
        { content: '流通股本', id: 'turnoverAmount' },
        { content: '总市值', id: 'totalValue' },
        { content: '流通市值', id: 'turnoverValue' },
        { content: '面值', id: 'facePrice' },
    ];

    // 要显示的表格列
    showFieldList: TFieldItem[] = [];

    // 已选择字段列表
    selectedFieldList: TFieldItem[] = [];
    // 固定字段列表
    fixedFieldList: TFieldItem[] = [
        { content: '交易市场', id: 'marketName' },
        { content: '证券代码', id: 'stockCode' },
        { content: '证券简称', id: 'stockNameSt' },
    ];
    // 表格勾选数据
    selectData: any[] = [];

    // 当前页或所有页
    pageType: string = '0';

    private showLayout: any[] = [];

    private notShowLayout: any[] = [];

    // private drag: boolean = false;

    private dict: Index = new Index();

    private marketCodeSelectData: any[] = []; // 交易市场下拉数据
    private stockTypeSelectData: any[] = [{ dictKey: '', dictKeyName: '' }]; // 证券类别下拉数据
    private moreTypeSelectData: any[] = []; // 更多分类下拉数据
    private mixTypeSelectData: any[] = []; // 杂项分类下拉数据
    private categoryTypeSelectData: any[] = []; // 证券类别下拉数据

    private fundMixedTypeMapping = {};
    private mixedTypeMapping = {};
    private bondMixedTypeMapping = {};

    private fundMoreTypeMapping = {};
    private bondMoreTypeMapping = {};
    private stockMoreTypeMapping = {};

    private stockType = {};

    private loading = false;
    private tableKey: number = 0;

    async mounted() {
        this.queryLayout();
        this.queryStockInfoList();
        // 获取证券类型下拉数据 stockType
        this.stockTypeSelectData = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        this.stockType = DictionConstUtil.ListToPojo(this.stockTypeSelectData);
        // 获取更多分类下拉数据
        // this.moreTypeSelectData = objToArr(this.dict.moreType);
        // 获取市场代码下拉数据
        this.marketCodeSelectData = await SGU_CACHE('MarketCode', '/dict/market/list', []);
        this.getDict();
        this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
    }

    beforeUpdate() {
        this.$nextTick(() => {
            // 在数据加载完，重新渲染表格
            (this.$refs['table'] as any).doLayout();
        });
    }

    // 重新渲染表头
    private renderHeader(h, { column, $index }) {
        let realWidth = 0;
        let span = document.createElement('span');
        // 设置表头名称
        span.innerText = column.label;
        // 临时插入documen
        document.body.appendChild(span);
        // 获取span最小宽度，设置当前列，注意这里加了50，字段较多时还是有挤压
        realWidth = span.getBoundingClientRect().width + 50;
        column.minWidth = realWidth; // 可能还有边距/边框等值，需要根据实际情况加上
        document.body.removeChild(span);
        return h('span', column.label);
    }

    // 证券信息分页
    private currentChange(): void {
        this.loading = true;
        let form = JSON.parse(JSON.stringify(this.queryForm));
        form.paging = this.stockPage;
        this.$axios
            .post('/stockInfo/list/data', form)
            .then((res: any) => {
                this.loading = false;
                (this.$refs.table as any).doLayout();
                this.stocktableData = res.list;
                this.stockPage.total = res.total;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    // 获取页面布局信息
    async queryLayout() {
        // this.loading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/TN_STOCK')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (!resList) {
            // 新用户初始化
            this.selectedFieldList = [
                { content: '证券全称', id: 'stockName' },
                { content: '证券类别', id: 'stockType' },
                { content: '资产类别', id: 'categoryTypeName' },
                { content: '面值', id: 'facePrice' },
                { content: '流通市值', id: 'turnoverValue' },
                { content: '总股本', id: 'totalAmount' },
                { content: '流通股本', id: 'turnoverAmount' },
                { content: '总市值', id: 'totalValue' },
            ];
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.selectedFieldList = this.tableColumns;
            } else {
                this.selectedFieldList = JSON.parse(resList);
            }
        }
        this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
        // this.loading = false;
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        this.loading = true;
        await this.queryLayout();
        this.loading = false;
    }

    private getDict() {
        getDictByCodes(['Y_000060', 'Y_000061', 'Y_000062', 'Y_000063', 'Y_000064', 'Y_000204']).then((data: any) => {
            if (data) {
                if (data.Y_000060) {
                    data.Y_000060.forEach(item => {
                        this.fundMixedTypeMapping[item.dictKey] = item.dictKeyName;
                    });
                }
                if (data.Y_000061) {
                    data.Y_000061.forEach(item => {
                        this.bondMixedTypeMapping[item.dictKey] = item.dictKeyName;
                    });
                }
                if (data.Y_000062) {
                    data.Y_000062.forEach(item => {
                        this.mixedTypeMapping[item.dictKey] = item.dictKeyName;
                    });
                    this.mixTypeSelectData = data.Y_000062.filter(item => item.dictKey !== '!');
                }
                if (data.Y_000063) {
                    data.Y_000063.forEach(item => {
                        this.fundMoreTypeMapping[item.dictKey] = item.dictKeyName;
                    });
                }
                if (data.Y_000064) {
                    data.Y_000064.forEach(item => {
                        this.bondMoreTypeMapping[item.dictKey] = item.dictKeyName;
                    });
                    this.moreTypeSelectData = data.Y_000064.filter(item => item.dictKey !== '!');
                }
                if (data.Y_000204) {
                    data.Y_000204.forEach(item => {
                        this.stockMoreTypeMapping[item.dictKey] = item.dictKeyName;
                    });

                    console.log(this.stockMoreTypeMapping);
                }
            }
        });
    }

    // 处理杂项分类和更多分类
    handleParams(obj, value) {
        let arr = value.split('');
        let showNames = [];
        arr.map(ele => {
            let value = obj[ele];
            value && showNames.push(value);
        });
        return showNames.join(',');
    }

    private queryStockInfoList() {
        this.loading = true;
        this.$axios
            .post('/stockInfo/list/data', {
                paging: {
                    currentPage: 1,
                    pageSize: 50,
                },
            })
            .then((res: any) => {
                // (this.$refs.tableBox as any).doLayout();
                this.stockCodeList = [];
                (this.$refs.table as any).clearSelection();
                this.loading = false;
                this.stocktableData = res.list;
                this.stockPage.total = res.total;
            })
            .catch(() => {
                this.loading = false;
            });
    }

    private handleSelectionChange(val: any) {
        this.stockCodeList = val.map(item => item.stockCode);
    }
    private openQueryDialog() {
        this.queryDialog = true;
    }

    // 重置查询表单
    private resetForm() {
        (this.$refs['queryForm'] as any).resetFields();
    }

    // 提交查询表单
    private submitQueryForm() {
        this.queryForm.paging.currentPage = 1;
        this.queryForm.paging.pageSize = this.stockPage.pageSize;

        this.loading = true;
        this.$axios
            .post('/stockInfo/list/data', this.queryForm)
            .then((res: any) => {
                // this.queryDialog = false;
                this.stocktableData = res.list;
                this.stockPage.total = res.total;
                this.stockPage.currentPage = 1;
                this.loading = false;
            })
            .catch(() => {
                this.loading = false;
            });
        this.queryDialog = false;
        this.tableKey++;
        this.stockCodeList = [];
    }

    // 导出
    private handleExport(val: string): void {
        let data: any = {};
        let form: any = {};
        form = JSON.parse(JSON.stringify(this.queryForm));
        form.paging = {
            currentPage: 0,
            pageSize: 0,
        };
        if (this.stockCodeList.length) {
            data = {
                stockCodes: this.stockCodeList,
            };
        } else {
            data = form;
        }

        if (this.stockCodeList.length == 0 && this.stockPage.total > 1000) {
            this.yh_message_error('导出数据量过大, 仅限导出1000条');
        } else if (this.stockCodeList.length > 1000) {
            this.yh_message_error('导出数据量过大, 仅限导出1000条');
        }
        downLoadFile({
            url: '/stockInfo/export',
            method: 'post',
            data: data,
            // loading: true,
            // loadingMsg: '正在准备导出，请稍后··· ···',
        });
    }
}
</script>
<style lang="scss" scoped>
.search-box {
    padding: 15px;
}
/deep/ .el-form {
    display: grid;
    grid-template-columns: 50% 50%;
    width: fit-content;
}
.title,
.content {
    border: 1px solid #d7d7d7;
    padding: 5px 10px;
}
.content {
    height: 300px;
}
.item {
    // height: 30px;
    padding: 5px;
    margin: 4px 2px;
    display: inline-block;
    border: 1px dashed #1890ff;
    border-radius: 3px;
}
/deep/ .el-table--border th:first-child .cell {
    padding-left: 6px;
}
</style>
